package io.github.talelin.latticy.service;

import io.github.talelin.autoconfigure.exception.ForbiddenException;
import io.github.talelin.latticy.common.UserUtil;
import io.github.talelin.latticy.dto.SendFlowerDTO;
import io.github.talelin.latticy.entity.SendCollect;
import io.github.talelin.latticy.repository.SendCollectRepository;
import io.github.talelin.latticy.vo.FlowerIdVO;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.SendCollectFlowerVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SendFlowerService
{
    @Autowired
    private SendCollectRepository sendCollectRepository;

    @Autowired
    private SendCollectService sendCollectService;

    public void updated(Long id, SendFlowerDTO dto)
    {
        SendCollect sendCollect = sendCollectService.get(id);
        //已查看
        if (sendCollect.getStatus() == 1) {
            throw new ForbiddenException(20002);
        }
        BeanUtils.copyProperties(dto, sendCollect);
        sendCollectRepository.save(sendCollect);
    }


    @Transactional
    public FlowerIdVO create(SendFlowerDTO dto)
    {
        SendCollect sendCollect = new SendCollect();
        sendCollect.setStatus(0);
        sendCollect.setSendUserId(UserUtil.getUserId());
        sendCollect.setCollectUserId(0L);
        BeanUtils.copyProperties(dto, sendCollect);
        sendCollectRepository.save(sendCollect);
        FlowerIdVO flowerIdVO = new FlowerIdVO();
        flowerIdVO.setId(sendCollect.getId());
        return flowerIdVO;
    }

    public PageResponseVO getFlowers(int page, int size)
    {
        Pageable pageable = PageRequest.of(page, size);
        Page<SendCollect> pager = sendCollectRepository.findBySendUserIdOrderByCreateTimeDesc(UserUtil.getUserId(), pageable);
        List<SendCollectFlowerVO> items = SendCollectFlowerVO.getLists(pager.getContent());
        return new PageResponseVO<>(pager.getTotalElements(), items, pager.getNumber(), pager.getSize());
    }
}
